<template>
	<a-drawer
		:open="open"
        :mask="false"
		:maskClosable="true"
		class="custom-class"
		root-class-name="root-class-name"
		:root-style="{ color: 'blue' }"
		:title="setTitle()"
		:width="720"
		placement="right"
		@close="onClose('govArea')"
	>
		<a-form :model="form" ref="formRef" :rules="rules" :label-col="labelCol" @submit.prevent="handleSubmit">
			
			<div v-if="areaType !='polygon'">

				<a-row :gutter="16">
					<a-col :span="12">
						<a-form-item label="省市县" name="provice">
							<a-cascader
								v-model:value="form.adname"
								ref="cascaderElement"
								@change="cascaderChange"
								name="provice"
								:options="cityData"
								defaultValue="东城区"
								placeholder="请选择"
							/>
						</a-form-item>
					</a-col>
				</a-row>
	
				<a-row :gutter="16">
					<a-col :span="12">
						<a-form-item label="过滤点数" name="glv">
							<a-select v-model:value="form.glv">
								<a-select-option value="20">20</a-select-option>
								<a-select-option value="15">15</a-select-option>
								<a-select-option value="10">10</a-select-option>
								<a-select-option value="0">0</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="">
							<a-space wrap>
								<a-button type="text" @click="extractDistrict"
									>提取区域边界</a-button
								>
								<a-button type="text" @click="toggleEdit">{{
									isEditing ? '停止编辑' : '开始编辑'
								}}</a-button>
							</a-space>
						</a-form-item>
					</a-col>
				</a-row>
			</div>


			<a-row :gutter="16">
				<a-col :span="12">
					<a-form-item label="区域名称" name="name">
						<a-input v-model:value="form.name" placeholder="请输入区域名称" />
					</a-form-item>
				</a-col>
				<a-col :span="12" v-if="areaType =='polygon'">
					<a-button type="text" @click="startDrawPolygon"
								>开始绘制</a-button
							>
					<a-button v-show="showStartEdit" type="text" @click="toggleEdit">{{
							isEditing ? '停止编辑' : '开始编辑'
						}}</a-button>
				</a-col>
			</a-row>
			<a-row :gutter="16">
				<a-col :span="24">
					<a-form-item label="进出提醒内容" name="txnr">
						<a-input
							v-model:value="form.txnr"
							placeholder="请输入进出提醒内容"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="16">
				<a-col :span="12">
					<a-form-item label="进入区域报警" name="alarmTypes">
						<a-checkbox-group
							v-model:value="form.checkedList1"
							:options="alarmTypes1slist"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="16">
				<a-col :span="12">
					<a-form-item label="离开区域报警" name="alarmTypes">
						<a-checkbox-group
							v-model:value="form.checkedList2"
							:options="alarmTypes2slist"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="16">
				<a-col :span="8">
					<a-form-item label="共享设置" name="byShare">
						<a-checkbox v-model:checked="form.byShare">全局共享</a-checkbox>
					</a-form-item>
				</a-col>
				<a-col :span="16">
					<a-form-item label="">
						注：勾选全局共享则为当前平台全部车辆生效
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="16">
				<a-col :span="8">
					<a-form-item label="属地配置" name="byDependency">
						<a-checkbox v-model:checked="form.byDependency">是否</a-checkbox>
					</a-form-item>
				</a-col>
				<a-col :span="16">
					<a-form-item label="">
						注：勾选属地配置，则该区域仅限用于设置车辆的归属地判断
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="16">
				<a-col :span="8">
					<a-form-item label="辖区设置" name="bymanor">
						<a-checkbox v-model:checked="form.bymanor">是否</a-checkbox>
					</a-form-item>
				</a-col>
				<a-col :span="16">
					<a-form-item label="">
						注：勾选辖区设置，则该区域仅限用于辖区限速配置
					</a-form-item>
				</a-col>
			</a-row>

			<!-- <a-row :gutter="16">
				<a-col :span="8">
					<a-form-item label="疫情风险" name="epidemicRisk">
						<a-select v-model:value="form.epidemicRisk">
							<a-select-option value="无风险">无风险</a-select-option>
							<a-select-option value="低风险">低风险</a-select-option>
							<a-select-option value="中风险">中风险</a-select-option>
							<a-select-option value="高风险">高风险</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="16">
					<a-form-item>
						注：可以设置该区域的疫情风险等级
					</a-form-item>
				</a-col>
			</a-row> -->

			<a-row :gutter="16">
				<a-col :span="8">
					<a-form-item label="时间设置" name="byTime">
						<a-checkbox v-model:checked="form.byTime">根据时间</a-checkbox>
					</a-form-item>
				</a-col>
				<a-col :span="16">
					<a-form-item label="限速设置" name="limitSpeed">
						<a-checkbox v-model:checked="form.limitSpeed">限速</a-checkbox>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="16">
				<a-col :span="8">
					<a-form-item label="限速(km/h)" name="maxSpeed">
						<a-input v-model:value="form.maxSpeed" placeholder="请输入限速" />
					</a-form-item>
				</a-col>
				<a-col :span="16" class="custom-label-width">
					<a-form-item label="停留报警时间(分钟)" name="delay">
						<a-input
							v-model:value="form.delay"
							placeholder="请输入停留报警时间"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="16">
				<a-col :span="18">
					<a-form-item label="时间范围" name="date">
						<a-space direction="vertical" :size="12">
							<a-range-picker v-model:value="form.date" show-time />
						</a-space>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="16">
				<a-col :span="20">
					<a-form-item label="坐标点" name="originGpsCoord">
						<div style="display: flex; align-items: center">
							<a-form-item-rest>
								<a-input v-model:value="form.points" placeholder="" />
							</a-form-item-rest>
							<a-checkbox v-model:checked="form.originGpsCoord" style="white-space: nowrap; margin-left: 15px"
								>原始坐标</a-checkbox
							>
						</div>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<template #extra>
			<a-space>
				<a-button @click="onClose('govArea')">取消</a-button>
				<a-button type="submit" @click="handleSubmit">保存</a-button>
			</a-space>
		</template>

	</a-drawer>
</template>

<script setup>
import { reactive, ref, defineProps, watch } from 'vue';
import cityData from '../static/localData/cityData';
import dayjs from 'dayjs';
import { saveItem, getItems, getItemById, deleteItem } from '../db';
import { message } from 'ant-design-vue'

const props = defineProps({
	catMap: Object,
	overlays: Object,
	updateOverlays: Function,
	updateAmenuTopList: Function,
	updateLineAndPolyList: Function,
    open: Boolean,
    id: Number,
    areaType: String,
    onClose:Function
});
let mouseTool = ref(null)
let showStartEdit = ref(false)
const formRef = ref(null);
const alarmTypes1slist = ['进区域报警给驾驶员', '进区域报警给平台'];
const alarmTypes2slist = ['进区域报警给驾驶员', '进区域报警给平台'];
const labelCol = {
	style: {
		width: '90px',
	},
};

const setTitle = ()=>{
	let title = ''
	let action = '创建'
	if(props.id > 0){
		action = '编辑'
	}
	if(props.areaType=='govArea'){
		title = '行政区域'
	} else if (props.areaType=='polygon'){
		title = '多边形区域'
	}
	return title + action
}

let formother = {
	provName: '',
	cityName: '',
	counName: '',
};
// 获取省市县文本
const cascaderChange = (value, selectedOptions) => {
	console.log(value, selectedOptions);
	formother.provName = selectedOptions[0]['label'];
	formother.cityName = selectedOptions[1]['label'];
	formother.counName = selectedOptions[2]['label'];
};

var styleOptions = {
    strokeColor:"red",    //边线颜色。
    fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 3,       //边线的宽度，以像素为单位。
    strokeOpacity: 0.8,	   //边线透明度，取值范围0 - 1。
    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'solid' //边线的样式，solid或dashed。
}

const startDrawPolygon = function () {
  mouseTool.value.polygon(styleOptions);
}

let FormData = {
	userName:'管理员',
	byShare: false,
	byDependency: false,
	bymanor: false,
	byTime: false,
	limitSpeed: false,
	originGpsCoord: false,
	areaType: props.areaType,
	maxSpeed: "90.0",
	startDate:'',
	endDate:'',
	epidemicRisk:'',
	delay: 10,
	glv: 20,
	date: [
		dayjs().startOf('month'),
		dayjs()
	],
	adname: '',
	name: '',
	txnr: '',
	points: '',
	alarmTypes1s: '',
	alarmTypes2s: '',
	alarmType:'',
	type: '',
	checkedList1: [],
	checkedList2: [],
	approver: '',
	dateTime: null,
	description: '',
}
let initFormData = JSON.parse(JSON.stringify(FormData))

const formDataByDB = ref(null);

watch(() => props.catMap, async (newId) => {
	mouseTool.value = new AMap.MouseTool(props.catMap)
	mouseTool.value.on('draw', overlaycomplete)
})

// 编辑在这
watch(() => props.id, async (newId) => {
  console.log(props.areaType,'ssss');
  formDataByDB.value = await getItemById('govArea',newId)
  //如果id是0就reset表单
  if (!newId) {
	  console.log(initFormData,'initFormData');
	for (const key in initFormData) {
		if (key == 'date') {
			form['date'] = [
				dayjs().startOf('month'),
				dayjs()
			]
		} else {
			form[key] = initFormData[key];
		}
	}
  }

  for (const key in formDataByDB.value) {
		if (formDataByDB.value.hasOwnProperty(key)) {
			if (key == 'date') {
				form['date'] = [dayjs(formDataByDB.value[key][0]),dayjs(formDataByDB.value[key][1])]
			} else {
				if (key == 'points' && formDataByDB.value['points']) {
					let lnglats = formDataByDB.value['points'].split(';')
					let path = lnglats.map(lnglat=>{
						return lnglat.split(',')
					})
					
					// 不该在每次编辑添加覆盖物, 因从覆盖物们中先找
					// 或许使用地图的获取全部覆盖物
					console.log(props.overlays,'overlays');
					let polygon
					let paddings = [160,200,400,400].map(val=>val*=.9)
					if (!props.overlays[newId]) {
						console.log(props.overlays[newId],'没有创建'+newId);
						polygon = new AMap.Polygon({
							path: path,
							strokeWeight: 2,
							strokeColor: '#ff0000',
							fillOpacity: 0.2,
							fillColor: '#1791fc',
							zIndex: 50,
						});
						props.catMap.add(polygon);
						props.overlays[newId] = polygon
						props.updateOverlays(props.overlays)
						
					} else {
						polygon = props.overlays[newId]
					}
					props.catMap.setFitView(polygon,false,paddings);
					polygonEditor.value = new AMap.PolygonEditor(props.catMap, polygon);
					
					polygonEditor.value.on('end', (event) => {
						console.log('编辑结束，最终多边形的路径:', event.target.getPath());
						form.points = event.target.getPath().join(';');
					});
				}
				form[key] = formDataByDB.value[key]; // 这将触发响应式更新  
			}
		}
	}
  console.log(form,'form');
});

var form = reactive(FormData);
const cascaderElement = ref(null);
const isEditing = ref(false);
const polygonEditor = ref(null);

const rules = {
	delay: [
		{
			required: true,
			message: '请输入停留报警时间(分钟)',
		},
	],
	maxSpeed: [
		{
			required: true,
			message: '请输入限速',
		},
	],
	name: [
		{
			required: true,
			message: '请输入区域名称',
		},
	],
	adname: [
		{
			required: true,
			message: '请选择行政区域',
		},
	],
};

const handleSubmit = (e) => {
	console.log(e,'e',formRef.value);
	
	if (formRef.value) {
		formRef.value.validate().then(async () => {
			const startDate = dayjs(form.date[0]).format('YYYY-MM-DD HH:mm:ss');
			const endDate = dayjs(form.date[1]).format('YYYY-MM-DD HH:mm:ss');
			form.createDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
			form.startDate = startDate
			form.endDate = endDate
			console.log(props.areaType,'props.areaType');
			form.areaType = props.areaType
			form.alarmType = form.checkedList1.join('，') + '，' +form.checkedList2.join('，')
			await saveItem(props.areaType, { ...form });
			setTimeout(() => {
				props.updateAmenuTopList()
				props.updateLineAndPolyList()
				mouseTool.value.close(true)
			}, 500);
			console.log(startDate,endDate);
			
			props.onClose()
		}).catch(error => {
		console.error('Validation failed:', error);
		});
	}
};

const toggleEdit = () => {
	if (isEditing.value) {
		polygonEditor.value.close();
	} else {
		form.points = '';
		polygonEditor.value.open();
	}
	isEditing.value = !isEditing.value;
};
function buildGovArea(provName, cityName, counName, step) {
	const districtSearch = new AMap.DistrictSearch({
		subdistrict: 0, //获取边界不需要返回下级行政区
		extensions: 'all', //返回行政区边界坐标等具体信息
		level: 'district', //查询行政级别为市
	});

	// const name = provName + cityName + counName;
	let name = counName != '市辖区' ? counName : cityName;

	function dsSearch(status, result){
		const boundaries = result.districtList[0].boundaries;
		if (boundaries) {
			props.catMap.clearMap();
			boundaries.forEach((boundary) => {
				let strPoints = boundary;
				if (step > 0) {
					const points = boundary.map((point) => [point.lng, point.lat]);
					strPoints = [];
					for (let i = 0; i < points.length; i += step) {
						strPoints.push(points[i]);
					}
				}
				const polygon = new AMap.Polygon({
					path: strPoints,
					strokeWeight: 2,
					strokeColor: '#ff0000',
					fillOpacity: 0.2,
					fillColor: '#1791fc',
					zIndex: 50,
				});
				let paddings = [160,200,400,400].map(val=>val*=.9)

				props.catMap.add(polygon);
				props.catMap.setFitView(polygon,false,paddings);

				// 其他
				form.points = strPoints.join(';');
				polygonEditor.value = new AMap.PolygonEditor(props.catMap, polygon);

				polygonEditor.value.on('end', (event) => {
					console.log('编辑结束，最终多边形的路径:', event.target.getPath());
					form.points = event.target.getPath().join(';');
				});
			});
		} else {
			console.error('未找到边界信息');
		}
	}
	districtSearch.search(name, (status, result) => {
		if (status === 'complete') {
			dsSearch(status, result)
		} else {
			console.error('获取边界失败: ', result);
			message.error('获取'+name+'边界失败，获取上一级的'+cityName)

			districtSearch.search(cityName, (status, result) => {
				if (status === 'complete') {
					dsSearch(status, result)
				}
			});
			
		}
	});
}

const extractDistrict = () => {
	console.log(form.adname, 'form.adname');
	if (!form.adname) {
		cascaderElement.value.focus();
		return false;
	}
	
	buildGovArea(
		formother.provName,
		formother.cityName,
		formother.counName,
		form.glv*1
	);
};


var overlaycomplete = function (e) {
  var geometric = e.obj;
  var strPoints = "";
  var points = []
  if (geometric.CLASS_NAME === "AMap.Polygon" || geometric.CLASS_NAME === "Overlay.Polygon") {
      var path = geometric.getPath(); // 获取折线或多边形的路径数组
      var sep = "";
      for (var i = 0; i < path.length; i++) {
        var pt = path[i];
        strPoints += sep + pt.lng + "," + pt.lat;
        sep = ";";
        points.push([pt.lng,pt.lat])
      }
      console.log(strPoints,'strPoints')
	  form.points = strPoints
      console.log(points,'points')
	  mouseTool.value.close(false);
		showStartEdit.value = true

	  polygonEditor.value = new AMap.PolygonEditor(props.catMap, geometric);

		polygonEditor.value.on('end', (event) => {
			console.log('编辑结束，最终多边形的路径:', event.target.getPath());
			form.points = event.target.getPath().join(';');
		});
	  
    }
};


</script>
<style>
.custom-label-width .ant-col {
	width: 140px !important;
}
</style>
